package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.dto.AwardVirtualInsideDTO;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.AwardVirtualCdkEntity;
import com.fjwt.gz.db.entity.AwardVirtualInsideEntity;
import com.fjwt.gz.db.vo.AwardVirtualInsideVO;
import com.fjwt.gz.service.mapper.AwardVirtualInsideMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  虚拟商品内部商品表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AwardVirtualInsideService extends ServiceImpl<AwardVirtualInsideMapper, AwardVirtualInsideEntity> {


    @Autowired
    private AwardVirtualCdkService awardVirtualCdkService;

    @Autowired
    private AgentInfoService agentInfoService;


    /**
     * 查询列表
     * @param iPage
     * @param awardVirtualInsideDTO
     * @return
     */
    public IPage<AwardVirtualInsideVO> queryList(IPage iPage, AwardVirtualInsideDTO awardVirtualInsideDTO) {
        IPage<AwardVirtualInsideVO> page = baseMapper.selectAwardVirtualInsideList(iPage,awardVirtualInsideDTO);
        List<AwardVirtualInsideVO> records = page.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            List<Long> insideIdList = records.stream().map(AwardVirtualInsideVO::getVirtualInsideId).toList();
            List<AwardVirtualCdkEntity> cdkEntityList = awardVirtualCdkService.list(AwardVirtualCdkEntity.gw()
                    .in(AwardVirtualCdkEntity::getVirtualInsideId, insideIdList));
            //通过内部商品id分组
            Map<Long, List<AwardVirtualCdkEntity>> insideIdMap = cdkEntityList.stream().collect(Collectors.groupingBy(AwardVirtualCdkEntity::getVirtualInsideId));
            records.forEach(entity -> {
                entity.setCdkNum(insideIdMap.getOrDefault(entity.getVirtualInsideId(), Collections.emptyList()).size());
            });
        }
        return page;
    }

    /**
     * 更新虚拟商品内部商品表
     * @param awardVirtualInsideDTO
     * @return
     */
    public void updateVirtualInside(AwardVirtualInsideDTO awardVirtualInsideDTO) {

        if (StringUtils.isBlank(awardVirtualInsideDTO.getGoodsName()) || awardVirtualInsideDTO.getGoodsPrice() == null
                || awardVirtualInsideDTO.getMarketPrice() == null || awardVirtualInsideDTO.getType() == null || awardVirtualInsideDTO.getVirtualInsideId() == null) {
            throw new BizException("请求参数不全，请检查！");
        }
        if (awardVirtualInsideDTO.getGoodsPrice() >= awardVirtualInsideDTO.getMarketPrice()) {
            throw new BizException("商品进价不能大于市场价，请检查！");
        }

        AwardVirtualInsideEntity virtualInsideEntity = getById(awardVirtualInsideDTO.getVirtualInsideId());
        if (virtualInsideEntity == null) {
            throw new BizException("该记录不存在！");
        }
        BeanUtil.copyProperties(awardVirtualInsideDTO, virtualInsideEntity);
        updateById(virtualInsideEntity);
    }

    /**
     * 获取Cdk详情 划拨功能回显
     * @param virtualInsideId 内部商品id
     * @return
     */
    public JSONObject getCdkDetail(String virtualInsideId) {
        if (virtualInsideId == null) {
            throw new BizException("请求参数不全，请检查！");
        }
        AwardVirtualInsideEntity insideEntity = getById(virtualInsideId);
        if (insideEntity == null) {
            throw new BizException("该记录不存在！");
        }
        //通过内部商品id查询Cdk
        List<AwardVirtualCdkEntity> awardCdkEntityList = awardVirtualCdkService.list(AwardVirtualCdkEntity.gw()
                .eq(AwardVirtualCdkEntity::getVirtualInsideId, insideEntity.getVirtualInsideId()));
        if (CollectionUtil.isEmpty(awardCdkEntityList)) {
            throw new BizException("当前商品没有CDK可划拨！");
        }
        JSONObject result = new JSONObject();
        result.put("total", awardCdkEntityList.size());
        result.put("usedNum", 0);
        result.put("unusedNum", 0);
        if (CollectionUtil.isNotEmpty(awardCdkEntityList)) {
            //过滤已划拨的Cdk
            List<AwardVirtualCdkEntity> hbCdkList = awardCdkEntityList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getAgentNo())).toList();
            result.put("usedNum", hbCdkList.size());
            result.put("unusedNum", awardCdkEntityList.size() - hbCdkList.size());
        }
        return result;
    }

    /**
     * 保存划拨cdk数量
     * @param insideDTO
     * @return
     */
    public void saveCdkNum(AwardVirtualInsideDTO insideDTO) {
        if (insideDTO.getVirtualInsideId() == null || StringUtils.isBlank(insideDTO.getAgentNo())) {
            throw new BizException("请求参数不全，请检查！");
        }
        AwardVirtualInsideEntity virtualInsideEntity = getById(insideDTO.getVirtualInsideId());
        if (virtualInsideEntity == null) {
            throw new BizException("所选内部商品不存在！");
        }
        List<AwardVirtualCdkEntity> virtualCdkEntityList = awardVirtualCdkService.list(AwardVirtualCdkEntity.gw()
                .eq(AwardVirtualCdkEntity::getVirtualInsideId, virtualInsideEntity.getVirtualInsideId())
                .and(isNotNull -> isNotNull.isNull(AwardVirtualCdkEntity::getAgentNo)
                        .or(isNOtBank -> isNOtBank.eq(AwardVirtualCdkEntity::getAgentNo, "")))
                .orderByAsc(AwardVirtualCdkEntity::getCreatedAt)
                .last(" limit " + insideDTO.getNum()));
        if (CollectionUtil.isNotEmpty(virtualCdkEntityList)) {
            AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(insideDTO.getAgentNo());
            virtualCdkEntityList.forEach(entity -> {
                entity.setAgentNo(agentInfo.getAgentNo());
                entity.setAgentNo1(agentInfo.getAgentNo1());
                entity.setAgentNo2(agentInfo.getAgentNo2());
                entity.setAgentNo3(agentInfo.getAgentNo3());
                entity.setAgentNo4(agentInfo.getAgentNo4());
            });
            awardVirtualCdkService.updateBatchById(virtualCdkEntityList);
        }
    }

    /**
     * 获取内部商品列表
     * @param awardVirtualInsideDTO
     * @return
     */
    public List<AwardVirtualInsideEntity> getList(AwardVirtualInsideDTO awardVirtualInsideDTO) {
        return baseMapper.selectList(AwardVirtualInsideEntity.gw());
    }
}
